package com.qf.commons.redis.lock.aop;

import com.qf.commons.core.utils.SpelUtils;
import com.qf.commons.redis.lock.CLock;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;

import java.lang.reflect.Method;

/**
 * description:
 * author: Ken
 * 公众号：Java架构栈
 */
@Aspect
@Order(1)
public class CLockAspect {

    @Around("@annotation(CsLock)")
    public Object lockAop(ProceedingJoinPoint joinPoint) throws Throwable {

        Object target = joinPoint.getTarget();
        System.out.println("目标对象：" + target.getClass().getName());

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        CsLock csLock = method.getAnnotation(CsLock.class);
        //获得锁的名称
        String key = csLock.value();//spel表达式

        //将key作为spel表达式进行解析
        String lockName = SpelUtils.getValue(key, method, joinPoint.getArgs(), String.class, null);

        try {
            //加锁
            CLock.bLock(lockName);
            //核心业务
            return joinPoint.proceed();
        } finally {
            //解锁
            CLock.unlock();
        }
    }
}
